package com.xjnt.tvos.tvlibs;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.xjnt.tvos.tvlibs.fragment.WebFragment;
import com.xjnt.tvos.tvlibs.jsbridge.BridgeManager;
import com.xjnt.tvos.tvlibs.jsbridge.IBridgeListener;
import com.xjnt.tvos.tvlibs.jsbridge.IServerCallback;
import com.xjnt.tvos.tvlibs.jsbridge.annotation.Callback;
import com.xjnt.tvos.tvlibs.jsbridge.annotation.Param;
import com.xjnt.tvos.tvlibs.jsbridge.data.ParamConsts;

public class MainActivity extends AppCompatActivity implements IBridgeListener.OnBridgeListener {

    private WebFragment mFragment;
    private BridgeManager bridgeManager;
    private NativeClass nativeClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initWebContainer();

        Button btn = findViewById(R.id.test_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                IJSClass jsClass = bridgeManager.createJSCommand(IJSClass.class);
                IJSClass.User user = new IJSClass.User();

                jsClass.test(user, new IServerCallback() {
                    @Callback
                    public void onReceive(
                            @Param(value = ParamConsts.KEY_RESPONSE_STATUS, type = Param.ParamType.STATUS) Integer status,
                            @Param(value = ParamConsts.KEY_RESPONSE_MSG, type = Param.ParamType.STATUS) String msg,
                            @Param(ParamConsts.KEY_RESPONSE_PARAMS) IJSClass.User rUser) {
                        Toast.makeText(MainActivity.this,
                                "收到JS返回:" + status + "|" + msg + "=>" + JSON.toJSONString(rUser),
                                Toast.LENGTH_LONG).show();

                    }
                });
            }
        });
    }

    protected void initWebContainer() {
        mFragment = new WebFragment();
        mFragment.setBridgeListener(this);
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.WebContainer, mFragment);
        ft.commit();
    }

    @Override
    public void onBridgeCreate(WebView mWebView) {
        bridgeManager = new BridgeManager(mWebView, "TVBridge.notifyFromNative");
        nativeClass = new NativeClass(MainActivity.this);
        bridgeManager.register(nativeClass);
        mWebView.addJavascriptInterface(bridgeManager, "NativeComm");
    }
}
